<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Cate;
use think\facade\Db;

/**
 * @extends Service<CateService>
 */
class CateService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['name'])) {
            $w[] = ['name', 'like', "%" . $searchQuery['name'] . "%"];
        }
        $w[] = ['is_delete', '=', 0];
        $map = Cate::where($w)->page($page, $limit)->order('sort', 'desc');
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    public function list($searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['name'])) {
            $w[] = ['name', 'like', "%" . $searchQuery['name'] . "%"];
        }
        $w[] = ['is_delete', '=', 0];
        $list = Cate::where($w)->select()->toArray();
        return [
            'list' => $list,
        ];
    }

    public function save($data, $cate_id = null)
    {
        Db::startTrans();
        try {
            if (empty($cate_id)) {
                Cate::create([
                    'name' => $data['name'],
                    'sort' => $data['sort'],
                ]);
            } else {
                $info = Cate::where('cate_id', $cate_id)->find();
                if (empty($info)) {
                    throw new \Exception('数据不存在');
                }
                $info->save([
                    'name' => $data['name'],
                    'sort' => $data['sort'],
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }

        return true;
    }

    public function del($id)
    {
        $info = Cate::where('cate_id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->save(['is_delete' => 1]);
    }
}